import { createStore } from "vuex";
import store from "./index";
import { dxget } from "../util/index";
let peer = null;
let conn = null; // 返回文本对象
let current = null; // call 对象
let dataConnection = null; // 建立文本连接
import {peerUrl,PeerConfig} from "../util/config"
export default createStore({
  state: {
    userName: "",
    TheActive: 0, // 通话的状态 0没有通话   1呼出  2.呼入 3.接通
    pitchOnNumber: null, //消息左侧选中
    ismsgopen: true, // 是否没有与会话连接
    TbleName: "",
    hangUpload: false, // 挂断按钮上的加载
    msg: {
      // 消息会话体
      destName: "", // 接收者账号
      fromName: "", // 发送者账号
      headPortrait: "", // 头像
      msgBody: "", // 消息
      userNickname: "", // 昵称
    },
    WhetherMultipleCalls: false, // 是否多人通话
    MultiplayerSessionList: [],
  },
  mutations: {
    /**
     * 初始化 peer
     * @param state
     * @param userName  // 用户账号
     */
    initPeerJs(state, userName) {
      state.userName = userName;
      initFun(state, userName);
    },
    /**
     * 拨号
     * @param state
     * @param callName  // 呼叫用户账号
     */
    dialCall(state, callName) {
      callFun(state, callName);
    },
    // 接听
    async switchOn(state) {
      let stream = await getstream();
      if (!stream) {
        window.$message.errmsg("没有摄像头");
        return;
      }
      current.answer(stream); // 把流传给对方
      HandleTheCall(state, conn);
    },
    // 挂断电话
    CancelOn(state) {
      state.hangUpload = true;
      store.state.isheader = true;
      if (state.TheActive == 1) {
        quxiaofun(state);
        current.close();
        conn.send("quxaio");
      }
      if (state.TheActive == 2) {
        quxiaofun(state);
        conn.send("quxaio");
      }
      if (state.TheActive == 3) {
        current.close();
      }
    },
    // 挂断电话
    closeCall(state) {
      current.close();
    },
    //设置聊天框选中
    setIdx(state, num) {
      state.pitchOnNumber = num;
    },
    setMsg(state, data) {
      state.msg = data;
    },
    destroy(state) {
      peer.destroy();
    },
    async getUserList(state, roomID) {
      let stream = await getstream();
      let { data }: any = await dxget("communication/conversational_guidance", {
        roomID: roomID,
      });
      data.map((a) => {
        if (localStorage.userNickname == a.userNickname) {
          a.src = stream;
        } else {
          a.src = "";
        }
      });

      state.MultiplayerSessionList = data;
    },
  },
});

const initFun = (state, userName) => {
  peer = new window.Peer(userName, {
    host: peerUrl,
    port: 8089,
    path: "/dxPeer",
    ...PeerConfig
  });
  peer.on("open", async (id) => {
    console.log("peerJs服务连接成功！我的账号是：" + id);
    // jbhs();
  });
  // 监听用户连接
  peer.on("connection", function (c) {
    conn = c;
    // conn.send("与用户" + c.id + "连接成功！");
    conn.on("data", function (data) {
      dataType(state, data);
    });
  });
  // 监听呼叫
  peer.on("call", async (call) => {
    // 多人通话
    if (state.WhetherMultipleCalls) {
      return;
    }

    if (state.TheActive == 3) {
      conn.send("thz");
      return;
    }
    current = call;
    state.TheActive = 2;
    state.TbleName = call.peer;
    store.state.isheader = false;
    const stream = await getstream();

    if (!stream) {
      quxiaofun(state);
      conn.send("NoCamera");
      return;
    }
    const myvideo: any = document.getElementById("CallingSideVideo");
    myvideo.srcObject = stream;
  });

  peer.on("close", function () {
    console.log("peer--close");
  });
  // 监听会话销毁了
  peer.on("destroy", function () {
    console.log("destroy");
  });
  /*监听会话销毁了 在这里可以做个断线重连*/
  peer.on("disconnected", function () {
    setTimeout(() => {
      peer.reconnect();
    }, 3000);
    console.log("disconnected");
  });

  // 会话错误信息钩子回调
  peer.on("error", function (e) {
    console.log("error", e);
    let str = "" + e;
    if (str.indexOf("Lost connection to server") >= 0) {
      // window.$message.error("连接视频服务失败");
      return;
    }
    if (str.indexOf("not connect") >= 0) {
      window.$message.error("对方可能没在线");
      return;
    }
    if (str.indexOf("is taken") >= 0) {
      //window.$message.error("检测此账号在其他的地方连接");
      return;
    }
  });
};

const callFun = async (state, callName) => {
  const stream = await getstream();
  if (!stream) {
    window.$message.error("无法与对方视频聊天，请检查摄像设备");
    return;
  }
  // 多人通话
  if (state.WhetherMultipleCalls) {
    return;
  }
  state.TheActive = 1;
  const myvideo: any = document.getElementById("CallingSideVideo");
  myvideo.srcObject = stream;
  let call = null;

  try {
    call = peer.call(callName, stream);
  } catch (e) {
    initFun(state, state.userName);
  }

  dataConnection = peer.connect(callName);
  dataConnection.on("open", function () {
    dataConnection.send("与用户" + state.userName + "连接成功！");
    dataConnection.on("data", function (data) {
      dataType(state, data);
    });
  });

  conn = dataConnection;
  current = call;
  console.log("呼叫对方:" + callName);
  HandleTheCall(state, dataConnection);
};

// 处理收到对方消息的处理类型
const dataType = (state, data) => {
  console.log(data);
  switch (data) {
    case "closecall":
      current.close();
      state.TheActive = 0;
      state.hangUpload = false;
      break;
    case "quxaio":
      quxiaofun(state);
      break;
    case "NoCamera":
      window.$message.error("呼叫失败：对方没有摄像头");
      quxiaofun(state);
      break;
    case "thz":
      window.$message.error("对方正在通话中请稍后在拨");
      quxiaofun(state);
      break;
  }
};
const quxiaofun = (state) => {
  state.TheActive = 0;
  state.hangUpload = false;
};
// 处理call事件
const HandleTheCall = (state, dataConnection) => {
  current.on("stream", (data) => {
    console.log("监听到了流call");
    console.log(data);
    state.TheActive = 3;
    const newsfriendvideo: any = document.getElementById("receivingEndVideo");
    newsfriendvideo.srcObject = data;
  });
  console.log(dataConnection);
  current.on("close", function (e) {
    console.log("监听呼叫--呼叫挂断了！");

    dataConnection.send("closecall");
  });
  current.on("error", function (err) {
    console.error("通话的状态异常了", err);
  });
  current.on("disconnect", function (err) {
    console.error("disconnect", err);
  });
};

const getstream = () => {
  return new Promise((resolve) => {
    // navigator.mediaDevices
    //   .getDisplayMedia({
    //     video: true,
    //     audio: false,
    //   })
    //   .then(function (stream) {
    //     resolve(stream);
    //   });

    var getUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia;
    getUserMedia(
      {
        audio: true,
        video: true,
      },
      function (stream) {
        resolve(stream);
      },
      function (err) {
        resolve(false);
      }
    );
  });
};

// const jbhs = async () => {
//   const stream = await getstream();
//   const myvideo: any = document.getElementById("CallingSideVideo");
//   myvideo.srcObject = stream;
// };
